<template>
  <div class="user-list-container">
    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card total-users" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40"><User /></el-icon>
            </div>
            <div class="stat-info">
              <p class="stat-label">总用户数</p>
              <p class="stat-value">{{ total }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card active-users" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40"><Checked /></el-icon>
            </div>
            <div class="stat-info">
              <p class="stat-label">正常用户</p>
              <p class="stat-value">{{ activeUsersCount }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card admin-users" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40"><Monitor /></el-icon>
            </div>
            <div class="stat-info">
              <p class="stat-label">管理员</p>
              <p class="stat-value">{{ adminUsersCount }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card new-users" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40"><UserFilled /></el-icon>
            </div>
            <div class="stat-info">
              <p class="stat-label">本月新增</p>
              <p class="stat-value">{{ newUsersCount }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="search-card" shadow="hover">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="searchForm.nickName" placeholder="请输入昵称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
        </div>
      </template>

      <el-table :data="userList" v-loading="loading" stripe style="width: 100%">
        <el-table-column prop="user_id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="nickName" label="昵称" width="150" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.role === 'admin' ? 'danger' : 'primary'">
              {{ row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="Number(row.status) === 1 ? 'success' : 'danger'">
              {{ Number(row.status) === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="注册时间" width="180">
          <template #default="{ row }">
            <el-icon style="margin-right: 5px"><Clock /></el-icon>
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" width="180">
          <template #default="{ row }">
            <el-icon style="margin-right: 5px"><Clock /></el-icon>
            {{ formatDateTime(row.lastLoginTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetail(row.user_id)">详情</el-button>
            <el-button size="small" type="primary" @click="showResetPassword(row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="display: flex; justify-content: flex-end; margin-top: 12px;">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, User, Checked, Monitor, UserFilled, Clock } from '@element-plus/icons-vue'
import request from '@/utils/request'

const router = useRouter()
const loading = ref(false)
const userList = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const sortBy = ref('createdAt')
const order = ref('DESC')

const searchForm = ref({
  username: '',
  nickName: '',
  status: null
})

// 统计数据计算
const activeUsersCount = computed(() => {
  return userList.value.filter(u => Number(u.status) === 1).length
})

const adminUsersCount = computed(() => {
  return userList.value.filter(u => u.role === 'admin').length
})

const newUsersCount = computed(() => {
  const now = new Date()
  const thisMonth = now.getMonth()
  const thisYear = now.getFullYear()
  return userList.value.filter(u => {
    if (!u.createdAt) return false
    const created = new Date(u.createdAt)
    return created.getMonth() === thisMonth && created.getFullYear() === thisYear
  }).length
})

// 格式化时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  try {
    const date = new Date(dateTime)
    if (isNaN(date.getTime())) return dateTime
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}`
  } catch {
    return dateTime
  }
}


// 获取用户列表
const getUserList = async () => {
  loading.value = true
  try {
    const response = await request.get('/admin/user/list', {
      params: {
        ...searchForm.value,
        page: page.value,
        pageSize: pageSize.value,
        sortBy: sortBy.value,
        order: order.value
      }
    })
    if (response.code === 0) {
      userList.value = response.data?.list || []
      total.value = Number(response.data?.total || 0)
    } else {
      ElMessage.error(response.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  getUserList()
}

// 重置
const handleReset = () => {
  searchForm.value = {
    username: '',
    nickName: '',
    status: null
  }
  page.value = 1
  getUserList()
}

// 查看详情
const viewDetail = (userId) => {
  router.push(`/admin/user/detail/${userId}`)
}

// 重置密码为默认密码
const showResetPassword = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要重置用户 ${user.username} 的密码吗？密码将被重置为默认密码：12345678`,
      '重置密码',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await request.put(
      `/admin/user/resetPassword/${user.user_id}`,
      null,
      {
        params: { newPassword: '12345678' }
      }
    )

    if (response.code === 0) {
      ElMessage.success('密码已重置为默认密码：12345678')
    } else {
      ElMessage.error(response.message || '密码重置失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置密码失败', error)
      ElMessage.error('密码重置失败')
    }
  }
}

onMounted(() => {
  getUserList()
})

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
  page.value = 1
  getUserList()
}
const handleCurrentChange = (val) => {
  page.value = val
  getUserList()
}
</script>

<style scoped>
.user-list-container {
  padding: 20px;
  background: #f0f2f5;
}

/* 统计卡片区域 */
.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 12px;
  transition: all 0.3s ease;
  cursor: pointer;
  border: none;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  width: 70px;
  height: 70px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}

.total-users .stat-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.active-users .stat-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.admin-users .stat-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.new-users .stat-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-label {
  margin: 0;
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  margin: 0;
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.search-form {
  margin: 0;
}

.table-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table__header) {
  font-weight: 600;
}

@media (max-width: 768px) {
  .stats-row {
    margin-bottom: 15px;
  }
  
  .stat-value {
    font-size: 24px;
  }
}
</style>
